package cn.itcast.ecshop.act;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import cn.itcast.ecshop.R;
import cn.itcast.ecshop.bean.request.CartRequest;
import cn.itcast.ecshop.bean.response.CartResponse;
import cn.itcast.ecshop.db.ShopCartManager;
import cn.itcast.ecshop.net.BaseReponse;
import cn.itcast.ecshop.net.BaseRequest;
import cn.itcast.ecshop.utils.Util;

public class ShopDemoActivity extends BaseActivity {

    private TextView textViewCartList;
    private EditText edit_num;
    private EditText edit_properties;
    private EditText edit_product_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_demo);
        textViewCartList = ((TextView) findViewById(R.id.textview_cart_list));
        edit_product_id = ((EditText) findViewById(R.id.edit_product_id));
        edit_num = ((EditText) findViewById(R.id.edit_num));
        edit_properties = ((EditText) findViewById(R.id.edit_properties));
    }

    Set<Integer> productProperties = new HashSet<>();

    public void addToCart(View view) {

        try {

            String productId = edit_product_id.getText().toString().trim();
            int id = Integer.parseInt(productId);

            String numStr = edit_num.getText().toString().trim();
            int num = Integer.parseInt(numStr);

            String properties = edit_properties.getText().toString().trim();
            if (!TextUtils.isEmpty(properties)) {

                productProperties.add(Integer.parseInt(properties));
            }

            ShopCartManager.addOrUpdateToCart(id, num, productProperties);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void getCart(View view) {

        try {
            String shopCartStr = ShopCartManager.getShopCartStr();

            Util.showTost(this, shopCartStr);
            Log.d("ShopDemoActivity", shopCartStr);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void clearShopCart(View view) {

        try {
            ShopCartManager.clearShopCart();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //发送请求获取数据
    public void goToCart(View view) {

        try {
            String sku = ShopCartManager.getShopCartStr();
            sendRequest(new CartRequest(sku), CartResponse.class);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onSuccessResult(BaseRequest request, BaseReponse response) {

        CartResponse cartResponse = (CartResponse) response;
        textViewCartList.setText(cartResponse.toString());
    }
}
